<?php

namespace app\admin\service;

use app\admin\dao\KeywordsDao;
use app\admin\dao\KnowledgeDao;
use app\admin\model\UM as UM;
use app\common\model\Keywords;
use app\common\model\Knowledge;
use ShidianUtil\Exception\DataNotExistException;
use ShidianUtil\Utils\StringUtil;
use ShidianUtil\Utils\TimeUtil;
use think\exception\ValidateException;

/**
 * Class KnowledgeService
 * @package app\knowledge\service
 */
class KnowledgeService
{
    private KnowledgeDao $knowledgeDao;
    private KeywordsDao $keywordsDao;

    public function __construct(KnowledgeDao $knowledgeDao, KeywordsDao $keywordsDao)
    {
        $this->knowledgeDao = $knowledgeDao;
        $this->keywordsDao = $keywordsDao;
    }

    /**
     * 法塘列表
     * @param \app\admin\model\UM|null $user
     * @param $categoryId
     * @param $isHot
     * @param $startTime
     * @param $endTime
     * @param $kw
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function index(?UM $user, $categoryId, $isHot, $startTime, $endTime, $kw, $keywordsId, ?int $page = null, ?int $page_size = null): array
    {
        if(is_numeric($endTime)){
            $endTime = TimeUtil::stamp(TimeUtil::DAY, $endTime, false);
        }

        $keywords = null;
        if (is_id($keywordsId)) {
            $keywords = Keywords::where('id', $keywordsId)->value('keywords');
        }

        return $this->knowledgeDao->listKnowledge($categoryId, $isHot, $startTime, $endTime, $kw, $keywords, $page, $page_size);
    }

    /**
     * 查询
     * @param \app\admin\model\UM|null $user
     * @param int $id
     * @return Knowledge
     */
    public function read(?UM $user, int $id): ?Knowledge
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->knowledgeDao->findKnowledge($id);
    }

    /**
     * 新增
     * @param \app\admin\model\UM $user
     * @param array $params
     * @return  Knowledge
     */
    public function add(UM $user, array $params): Knowledge
    {
        $params['userId'] = $user->id;
        $params['checkStatus'] = 1;

        $this->checkRepeat($params['title']);

        params_enums($params, 'isHot', 0, 1);

        if (not_blank($params['keywords'])) {
            $params['keywords'] = StringUtil::trim(StringUtil::replace($params['keywords'], ['，'], ','), ', ');
        }

        $record = $this->knowledgeDao->insertActive($params, []);

        $this->saveKeywords($params['keywords']);

        return $record;
    }

    /**
     * 更新
     * @param \app\admin\model\UM $user
     * @param int $id
     * @param array $params
     * @return \app\common\model\Knowledge
     */
    public function modify(UM $user, int $id, array $params): Knowledge
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = Knowledge::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该法塘不存在或已被删除');
        }

        $this->checkRepeat($params['title'], $id);

        params_enums($params, 'isHot', 0, 1);

        if (not_blank($params['keywords'])) {
            $params['keywords'] = StringUtil::trim(StringUtil::replace($params['keywords'], ['，'], ','), ', ');
        }

        $allowField = ['categoryId', 'smallPic', 'title', 'content', 'isHot', 'keywords'];
        $this->knowledgeDao->updateActive($record, $params, $allowField);

        $this->saveKeywords($params['keywords']);

        return $record;
    }

    /**
     * 删除
     * @param \app\admin\model\UM $user
     * @param int $id
     */
    public function rm(UM $user, int $id): void
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = Knowledge::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            return;
        }

        $this->knowledgeDao->deleteModel($record);
    }

    private function checkRepeat($name, $id = null)
    {

        $record = Knowledge::where('title', $name)
            ->when(is_id($id), function ($query) use ($id) {
                $query->where('id', '<>', $id);
            })
            ->find();

        if (!is_null($record)) {
            throw new ValidateException('该分类已存在');
        }
    }

    public function saveKeywords($keywords): void
    {
        if (is_blank($keywords)) {
            return;
        }

        $keywords = explode(',', $keywords);

        // 保存
        foreach ($keywords as $keyword) {

            $keyword = StringUtil::trim($keyword);

            try {

                $params = [
                    'keywords' => $keyword,
                ];
                $this->keywordsDao->insertActive($params);
            } catch (\Exception $exception) {

            }
        }
    }
}
